<template>
  <j-modal
    :title="title"
    width="395px!important"
    height="300px"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class: { 'jee-hidden': true } }"
    @cancel="handleCancel"
    :cancelButtonProps="{ class: { 'jee-hidden': true } }"
    cancelText="关闭"
  >
    <img :src="qrCodeData" style="width:350px;height: 350px;" />
    <div style="text-align: center;">
      <a-button type="primary" icon="download" size="small" @click="downloadFile()">
        下载
      </a-button>
    </div>
  </j-modal>
</template>

<script>
import qrcode from 'qrcode'
export default {
  name: 'EneDeviceQrcodeModal',
  components: {},
  data() {
    return {
      title: '设备二维码',
      visible: false,
      disableSubmit: false,
      qrCodeData: ''
    }
  },
  methods: {
    detail(record) {
      this.visible = true
      this.title = '设备二维码 ' + record.deviceId
      qrcode.toDataURL(record.deviceId, { version: 5, width: 500, height: 500 }, (err, url) => {
        if (err) {
          console.error(err)
        } else {
          this.qrCodeData = url
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    downloadFile() {
      const a = document.createElement('a')
      // 将 a 标签的 download 属性设置为要下载的文件名
      a.download = this.title || 'image'
      // 创建 Blob 对象，并获取 base64 数据的 MIME 类型
      const mimeType = this.qrCodeData.match(/:(.*?);/)[1]
      // 将 base64 数据转换为字节数组
      const byteCharacters = atob(this.qrCodeData.split(',')[1])
      const byteNumbers = new Array(byteCharacters.length)
      // 将字节数组填充到 Uint8Array 中
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      // 创建 Blob 对象
      const blob = new Blob([byteArray], { type: mimeType })
      // 将 Blob 对象的 URL 赋值给 a 标签的 href 属性
      a.href = URL.createObjectURL(blob)
      // 将a标签暂时添加到 body 中，触发下载
      document.body.appendChild(a)
      a.click()
      // 下载完成后，将 a 标签从 body 中移除
    },
    handleOk() {
      this.$refs.realForm.submitForm()
    },
    submitCallback() {
      this.$emit('ok')
      this.visible = false
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>
